package com.example.springboot.config.registerBean;

import com.example.springboot.dao.registerBean.IUserDao;
import com.example.springboot.entity.User;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import javax.sql.DataSource;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 注册的代理类的bean工厂
 *
 * @Author:ChenZhangKun
 * @Date: 2021/4/2 13:49
 */
public class ProxyBeanFactory implements FactoryBean {
    @Autowired
    @Qualifier("alibaba")
    private DataSource dataSource;

    @Override
    public Object getObject() throws Exception {
        // 生成代理对象
        // 拿到上下文类加载器
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        // 拿到字节数组
        Class[] classes = {IUserDao.class};
        // 实现代理接口
        InvocationHandler invocationHandler = ((proxy, method, args) -> {
            // 拿到注解
            if (method.isAnnotationPresent(CzkSelect.class)) {
                // 拿到sql
                CzkSelect annotation = method.getAnnotation(CzkSelect.class);
                //
                String sql = annotation.value();
                if (!Objects.equals(sql, "")) {
                    // 执行sql
                    Connection connection = dataSource.getConnection();
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    // 拿到结果集
                    ResultSet resultSet = preparedStatement.executeQuery();
                    // 封装
                    List<User> list = new ArrayList<>();
                    while (resultSet.next()) {
                        // 游标
                        User user = new User();
                        // id
                        user.setId(resultSet.getInt(1));
                        // email
                        user.setEmail(resultSet.getString(2));
                        // lase_name
                        user.setLastName(resultSet.getString(3));
                        list.add(user);
                    }
                    return list;
                }
            }
            // 代理对象名称
            return "代理对象";
        }
        );
        InvocationHandler invocationHandler1 = (proxy, method, args) -> "你被代理了" + method.getName();
        // 返回代理对象
        return Proxy.newProxyInstance(contextClassLoader, classes, invocationHandler);
    }

    @Override
    public Class<?> getObjectType() {
        return IUserDao.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
